package com.jiang.filter;

import com.jiang.dao.userimpl;
import com.jiang.entity.User;
import com.jiang.service.Administratorimpl;
import com.jiang.utlis.Base64Utils;
import com.jiang.utlis.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jiangjingbo
 * @version V1.0
 * @Project java2203
 * @Package com.jiang.filter
 * @Description:
 * @Date 2022/5/23 23:27
 */
@WebFilter("/login.jsp")
public class AutoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest)servletRequest;
        //获取cookies
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            String content =null;  //用于存储账号和密码
            //本地存储了 cookies的值
            for (Cookie cookie : cookies) {

                //因为cookies中存储了多个cookie 需要判断我们存储的cookie是否一致
                if(cookie.equals(Constants.AUTO_NAME)){
                    content= cookie.getValue();
                }
            }
            if(content != null){
                //读取到课cookie的账号和密码
                content= Base64Utils.decode(content);
                //split 方法切割
                String[] split = content.split(Constants.FLAG);
                String username = split[0];
                String pwd = split[1];
                
                //调用业务层
                Administratorimpl user = new Administratorimpl(new userimpl());
                User user1 = user.selectUser(username,pwd);
                if (user1 != null) {
                    request.getSession().setAttribute("loginUser",user);
                    HttpServletResponse response =(HttpServletResponse) servletResponse;
                    response.sendRedirect(request.getContextPath()+"/index.jsp");
                }else {
                    //防止修改密码 如果修改直接放行
                    filterChain.doFilter(servletRequest,servletResponse);
                }
            }else {
                //放行
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }else {
            //没有cookies的值 放行
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
